#ifndef _UDP_SOCKET_SERVER_
#define _UDP_SOCKET_SERVER_
#include "../common/head.h"
#include "Message.h"
#include "../net/IMsgDispatcher.h"

class UDPSocketServer{
	public:
		UDPSocketServer(IMsgDispatcher* imp,int port){
			_imd = imp;
			Init(port);

		}

		void Init(int port){
			if((_ssock=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP))<0){
				LOG(ERROR)<<"socket create error!";
				exit(1);
			}
			memset(&_server_addr,0,sizeof(_server_addr));
			_server_addr.sin_family = AF_INET;
			_server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
			_server_addr.sin_port = htons(port);

			if(bind(_ssock,(struct sockaddr *)&_server_addr,sizeof(_server_addr))<0){
				LOG(ERROR)<<"error bind..";
			}
		}
		~UDPSocketServer(){

		}

		void receive_msg(){
			char buff[2048];
			socklen_t addrlen;
			int msg_len;
			struct sockaddr_in client_addr;
			int last_zeit=0; 
			while(1){
				memset(buff,0,2048);
				msg_len=recvfrom(_ssock,buff,2048,0,
						(struct sockaddr *)&client_addr,&addrlen);
				buff[msg_len]='\0';
				LOG(INFO)<<"Receive "<<buff;
				//add queue
				if(time(NULL)>(last_zeit)){
					last_zeit = time(NULL);
					std::string msg_str(buff);
					int split_zone_index = msg_str.find("|");
					if(split_zone_index == -1){
						continue;
					}
					std::string zone_id_str = msg_str.substr(0,split_zone_index);
					short zone_id =(short) atoi(zone_id_str.c_str());
					std::string tmp_string = msg_str.substr(split_zone_index+1,msg_str.size());
					int split_name_index = tmp_string.find("|");
					if(split_name_index == -1){
						continue;
					}
					std::string user_id_str = tmp_string.substr(0,split_name_index);
					int user_id = atoi(user_id_str.c_str());
					int msg_size = msg_len -1-split_zone_index + sizeof(UserChatMsg);
					char* msg_buff = new char[msg_size];
					UserChatMsg* msg = (UserChatMsg*)msg_buff;
					msg->message_type= SYS_AUTO_CHAT;
					msg->msg_size    = msg_size;
					msg->msg_type	 = CHAT_MSG;
					msg->is_encode   = 0;
					msg->sender_id = user_id;
					msg->world_id = zone_id;
					msg->message_len = msg_len - split_name_index-split_zone_index -2;
					memcpy(msg->message_content,buff+split_name_index+2+split_zone_index,msg_len-1-split_zone_index);
					_imd->add_msg_to_queue((MsgBase*)msg,NULL);				
				}
			}
		}

	private:
		int _ssock;
		struct sockaddr_in _server_addr;
		IMsgDispatcher* _imd;
};

#endif
